<?php

class ClaseController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(array('CrugeAccessControlFilter'));
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete'),
                'users' => array('10000'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Clase;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Clase'])) {
            $model->attributes = $_POST['Clase'];
			
			//se esta editando la clase
			$idClaseModif = $_POST['id_clase_modif'];
			if($idClaseModif != ''){
				Yii::log('editando clase','info','ClaseController');
				Yii::app()->user->setState('idClase', $idClaseModif); 
                Yii::app()->user->setState('idCurso', $model->id_curso);
				$this->redirect(Yii::app()->createUrl('asistencia/index'));
			}
			Yii::log(isset($model->id_clase) ? 'set' : 'not set','info','ClaseController');
			
			
            $curso = $model->id_curso;
            $fecha =  date('Y-m-d');
            $model ->getError('error');

            if ($curso != 0) {
                $soapClient = new SoapClient(Yii::app()->getParams()->webServiceUrl);
                $response = $soapClient->getCantHoraMateria($curso, $fecha);
               
                if ($response == 0) {
                    $queryRecuperacion = "select id_recuperacion from recuperacion where id_curso = $curso and fecha_recuperacion = '$fecha';"; 
                    $idRecuperacion = Yii::app()->db->createCommand($queryRecuperacion)->queryRow();
                    if ($idRecuperacion == null) {
                        throw new CHttpException(500, 'La clase ('.$fecha.') que intenta crear no esta calendarizada para clase ni para recuperacion.');
                    }
                }

                $queryAsistencia = "select * from clase where id_curso = $curso and fecha = '$fecha';"; 
                $query = Yii::app()->db->createCommand($queryAsistencia)->queryRow();
                
                if ($query == NULL) {
                    
                    $queryString = "select checkHour from cruge_system where idsystem=1;";
                    $check = Yii::app()->db->createCommand($queryString)->queryRow();
                    if($check['checkhour']){
                        $hora_finalizacion = $soapClient->getMateriaHorarioInicio($curso, date('Y-m-d'));
                        $hour = $soapClient->getCantHoraMateria($curso, date('Y-m-d'));
                        $hora_final_clase = date('H:i', strtotime($hora_finalizacion . ' + ' . ($hour * 40) . 'minutes'));
                        $hora_inicio_clase = date('H:i', strtotime($hora_finalizacion));
                        
                        Yii::log(CVarDumper::dumpAsString($hora_finalizacion),'warning','$hora_finalizacion');
			Yii::log(CVarDumper::dumpAsString($hour),'warning','$hour');
			Yii::log(CVarDumper::dumpAsString (date('Y-m-d H:i:s e')),'warning','date');
			Yii::log(CVarDumper::dumpAsString($hora_inicio_clase),'info','$hora_inicio_clase');
			Yii::log(CVarDumper::dumpAsString($hora_final_clase),'error','$hora_final_clase');

                        if ((date('H:i') > $hora_final_clase) || (date('H:i') < $hora_inicio_clase)) { 
                         //$this->redirect(Yii::app()->homeUrl);
                             throw new CHttpException(500, 'La clase ('.$fecha.') que intenta crear no esta calendarizada para este horario. Verificar la hora de clase.');

                         }
                    } 
                                       
                    $model->save();
                     $clase = $model->id_clase;
                    Yii::app()->user->setState('idClase', $clase); 
                    Yii::app()->user->setState('idCurso', $model->id_curso); 
                    $queryRecuperacion = "update recuperacion set id_clase = $clase where id_curso = $curso and fecha_recuperacion = '$fecha';"; 
                     Yii::app()->db->createCommand($queryRecuperacion)->query();
						
                    $soapClient = new SoapClient(Yii::app()->getParams()->webServiceUrl);

                    $query = $soapClient->getAlumnoXCurso($curso);

                    foreach ($query as $alumno) {
                        $queryAsistencia = "INSERT INTO asistencia VALUES ($alumno,$curso,$model->id_clase,0);"; 
                        Yii::app()->db->createCommand($queryAsistencia)->queryRow();
                    }
                    $this->redirect(Yii::app()->createUrl('asistencia/index'));
                    
                    
                }else{
                    throw new CHttpException(500,'Ya existe una clase creada el dia '.$fecha.'');
                }
                  
            } else {
                throw new CHttpException(404, 'No se ha selecccionado ningun curso.');
            }
        }


        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Clase'])) {
            $model->attributes = $_POST['Clase'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id_clase));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
		
		//borrar en asistencia todas las assitencias de esa clase (y recuperacion)
		$queryString = "delete from recuperacion where id_clase=$id;";
		$query = Yii::app()->db->createCommand($queryString)->queryAll();
		
		$queryString = "delete from asistencia where id_clase=$id;";
		$query = Yii::app()->db->createCommand($queryString)->queryAll();
		
		
        $this->loadModel($id)->delete();
		
		

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Clase');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Clase('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Clase']))
            $model->attributes = $_GET['Clase'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return Clase the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = Clase::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param Clase $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'clase-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionMateriaId() {
        $idCurso = Yii::app()->request->getParam('id_curso', 0);
        $soapClient = new SoapClient(Yii::app()->getParams()->webServiceUrl);
        $query = $soapClient->getCurso($idCurso);
		
		$array = array();
		$array['idMateria'] = $query['pe_asignatura_id'];
		$array['observacion'] = '';
	
		$fecha = date("Y-m-d");
		$queryString = "select fecha_clase from recuperacion where fecha_recuperacion='$fecha' and id_curso=$idCurso;";
		$query = Yii::app()->db->createCommand($queryString)->queryRow();
		if($query){
			$array['observacion'] = 'Recuperacion clase fecha '.$query['fecha_clase'];
		}
		$queryString = "select * from clase where fecha='$fecha' and id_curso=$idCurso;";
		$query = Yii::app()->db->createCommand($queryString)->queryRow();
		if($query){
			$array['modificar'] = true;
			$array['tema'] = $query['tema_materia'];
			$array['observacion'] = $query['observacion'];
			$array['id_clase'] = $query['id_clase'];
		}else{
			$array['modificar'] = false;
		}
		
        header("Content-type: application/json");
        echo json_encode($array);
    }
	
	public function getNombreCurso($idCurso)
	{
		$soapClient = new SoapClient(Yii::app()->getParams()->webServiceUrl);
		$curso = $soapClient->getCurso($idCurso);
		$materia = $soapClient->getMateria($curso['pe_asignatura_id']);
		return $materia['nombre'];
	}
}